package com.lzf.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.code.kaptcha.Producer;
import com.lzf.domain.Users;
import com.lzf.domain.dto.ReturnValue;
import com.lzf.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.PrintWriter;

@RestController
public class KaptchaCodeController {
    @Autowired
    private Producer captchaProducer;

    @RequestMapping(value = "/captchaCode")
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取实际公网ip，依赖nginx 代理配置设置请求头 proxy_set_header   X-Real-IP        $remote_addr;
        //server {
        //    listen       9999;
        //    server_name  localhost;
        //
        //    location / {
        //            proxy_pass http://192.168.12.85:8080;
        //    proxy_set_header   Host             $host;
        //    proxy_set_header   X-Real-IP        $remote_addr;
        //    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        //}
        //}
        String ip = request.getHeader("X-Real-IP");
        String remoteAddr = request.getRemoteAddr();
        String ip2 = request.getHeader("X-Forwarded-For");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        String captchaType = request.getParameter("captchaType");

        //生成文字验证码
        String text = captchaProducer.createText();
        if(StringUtils.isEmpty(captchaType) || captchaType.equals("1")){
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(new ObjectMapper().writeValueAsString(new ReturnValue<String>(text)));
            writer.flush();
            writer.close();
        }else if(captchaType.equals("2")) {
            //生成图片验证码
            response.setContentType("image/jpeg");
            BufferedImage image = captchaProducer.createImage(text);
            ServletOutputStream out = response.getOutputStream();
            ImageIO.write(image, "jpg", out);
            out.flush();
            out.close();
        }
        RedisUtils.set(ip,text,300);

    }

}
